<template>
  <!-- <main-header style="z-index: 999;"></main-header> -->
  <!-- <app-center></app-center> -->
  <div class="dataCenter-board-template">
    <!-- 顶部菜单 -->
    <div class="templateHeader">
      <div class="templateHeader-left">
        <!-- {{ currentMenuName }} -->
        &nbsp;&nbsp;数据概况
        &nbsp;
        <el-tooltip v-if="tooltipContent" class="item" effect="light" placement="right-start">
          <template #content>
            <div style="overflow-y: auto;height: 400px;" v-html="tooltipContent"></div>
          </template>
          <img class="handle-tanhao" :src="tanhao" alt="">
        </el-tooltip>
      </div>
      <div class="templateHeader-right">
        <el-form :inline="true" :model="form" class="demo-form-inline">
          <!-- <el-form-item label="机构切换:">
            <el-cascader
              v-model="form.organizationId"
              clearable
              :options="orgOptions"
              :props="props"
              @change="handleChangeOrganization" />
          </el-form-item> -->
          <el-form-item label="时间:">
            <el-date-picker style="width: 330px;" v-model="form.date" type="datetimerange"
              value-format="YYYY-MM-DD HH:mm:ss" :default-time="[new Date(2000, 1, 1, 0, 0, 0),
              new Date(2000, 2, 1, 23, 59, 59),]" unlink-panels range-separator="~" start-placeholder="开始时间"
              end-placeholder="结束时间" :shortcuts="shortcuts" :size="size" @change="handleChangeDate" />
          </el-form-item>
          <!-- <el-form-item label="活动搜索:">
            <el-input v-model="form.chartName" clearable placeholder="请输入活动名称" style="width: 170px;"></el-input>
          </el-form-item> -->
          <!-- <el-button type="primary" @click="">搜索</el-button> -->
          <el-button type="primary" @click="merchantReportProvideUpdaApi">更新保存</el-button>
        </el-form>
      </div>
    </div>
    <!-- 全部组件template -->
    <div class="templateComponents" v-if="templateList.length != 0">
      <draggable id="draggable" :component-data="{
        tag: 'div',
        type: 'transition-group',
      }" v-model="templateList" v-bind="dragOptions" @start="drag = true" @end="drag = false" item-key="beanName">
        <template #item="{ element }">
          <div class="list-group-item" :class="[
            element.layoutType === 'medium' ? 'medium'
              : (element.layoutType === 'small' ? 'small' : 'mini'),
            element.largeHeight ? 'largeHeight' : ''
          ]
            ">
            <!-- 拖拽handle -->
            <div class="dragIcon">
              <img class="handle" :src="handleMove" alt="">
            </div>
            <!-- 操作opera -->
            <div class="operaIcon">
              <el-dropdown @command="handleCommand($event, element)">
                <img class="more" :src="handleMore" alt="">
                <template v-slot:dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="edit">编辑</el-dropdown-item>
                    <el-dropdown-item command="export"
                      v-if="element.support && element.support.includes('table')">数据下载</el-dropdown-item>
                    <el-dropdown-item v-if="['line', 'lineTrend', 'bar'].includes(element.type) && element.showFilterData"
                      command=" dataScreen">数据展示筛选</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
            <!-- 指标Component -->
            <Indicator v-if="element.type === 'indicator'" v-model:id="element.beanName"
              v-model:chartName="element.chartName" :service="service">
            </Indicator>

            <!-- 折线图Component -->
            <LineChart v-if="element.type === 'line'" v-model:id="element.beanName" v-model:chartName="element.chartName">
            </LineChart>

            <!-- 指标卡趋势图Component -->
            <LineTrendChart v-if="element.type === 'lineTrend'" v-model:id="element.beanName"
              v-model:chartName="element.chartName">
            </LineTrendChart>

            <!-- 柱状图Component -->
            <BarChart v-if="element.type === 'bar'" v-model:id="element.beanName" v-model:chartName="element.chartName">
            </BarChart>

            <!-- 饼图Component -->
            <PieChart v-if="element.type === 'pie'" v-model:id="element.beanName" v-model:chartName="element.chartName">
            </PieChart>

            <!-- 排名Component -->
            <Ranking v-if="element.type === 'ranking'" v-model:id="element.beanName"
              v-model:chartName="element.chartName">
            </Ranking>

            <!-- 表格Component -->
            <CommonTable v-if="element.type === 'table'" v-model:id="element.beanName"
              v-model:chartName="element.chartName">
            </CommonTable>

            <!-- 漏斗图Component -->
            <FunnelChart v-if="element.type === 'funnel'" v-model:id="element.beanName"
              v-model:chartName="element.chartName">
            </FunnelChart>
          </div>
        </template>
      </draggable>
    </div>
    <!-- 无图表展示Icon -->
    <div class="templateComponents-else" v-else>
      <div class="empty">
        <p class="empty-img">
          <img class="img" :src="indexEmpty" alt="">
        </p>
        <p class="empty-text">
          您还未添加任何图表，快去添加图表吧
        </p>
        <p class="empty-btn">
          <!-- <el-button type="primary" @click="handleClickAppendChat">添加图表</el-button> -->
        </p>
      </div>
    </div>
    <!-- 添加图表Dialog -->
    <AppendChatDialog v-model:visible="appendChatVisible" v-model:reportLinkChart="reportLinkChart"
      v-model:beanName="beanName" @handleClickConfirm="handleClickConfirm">
    </AppendChatDialog>
    <!-- 动态导出多级表头excel -->
    <div class="templateComponents-table">
      <el-table id="outTable" ref="report-table" :data="tableData" style="width: 100%;height: 230px;"
        header-cell-class-name="headerCellClass">
        <template v-for="( item, index ) in  column " :key="index">
          <el-table-column :width="item.width ? item.width : 'auto'" :prop="item.prop"
            :align="item.align ? item.align : 'center'" :label="item.label">
            <template #default="scope" v-if="item.isNested ? item.isNested : false">
              <el-table-column v-for="( value, key ) in  item.childrenColumn " :key="key"
                :width="value.width ? value.width : 'auto'" :prop="value.prop"
                :align="value.align ? value.align : 'center'" :label="value.label">
                <template #default="scope">
                  <slot v-if="value.slot" :name="value.prop" :row="scope.row"></slot>
                  <template v-else>
                    {{ scope.row[value.prop] }}
                  </template>
                </template>
              </el-table-column>
            </template>
            <template #default="scope" v-else>
              <slot v-if="item.slot" :name="item.prop" :row="scope.row"></slot>
              <template v-else>
                {{ scope.row[item.prop] }}
              </template>
            </template>
          </el-table-column>
        </template>
      </el-table>
    </div>
    <!-- 新建看板 -->
    <BoardDialog v-model:visible="boardVisible" v-model:id="boardId" v-model:organizationId="form.organizationId"
      @handleUpdateMenu="handleUpdateMenu">
    </BoardDialog>
    <!-- 新建分组 -->
    <GroupDialog v-model:visible="groupVisible" v-model:id="groupId" v-model:organizationId="form.organizationId"
      @handleUpdateMenu="handleUpdateMenu">
    </GroupDialog>
    <!-- 移动分组 -->
    <MobileBoardDialog v-model:visible="mobileBoardVisible" @handleUpdateMenu="handleUpdateMenu">
    </MobileBoardDialog>
  </div>
</template>

<script>
// 基础
import draggable from "vuedraggable";
import AppendChatDialog from './component/appendChatDialog.vue';
import handleMove from '@/assets/dataCenter/dataBoard_move.png';
import handleMore from '@/assets/dataCenter/dataBoard_more.png';
import tanhao from '@/assets/dataCenter/icon-tanhao.png';
import { ElMessage, ElMessageBox } from "element-plus";
import BoardDialog from './component/boardDialog.vue';
import GroupDialog from './component/groupDialog.vue';
import MobileBoardDialog from './component/mobileBoardDialog.vue';
// 组件
import Indicator from './component/indicator.vue';
import LineChart from './component/lineChart.vue';
import LineTrendChart from './component/lineTrendChart.vue';
import BarChart from './component/barChart.vue';
import PieChart from './component/pieChart.vue';
import Ranking from './component/ranking.vue';
import CommonTable from './component/commonTable.vue';
import FunnelChart from './component/funnelChart.vue';
// API
import {
  dataBoardByReportMenuId,
  dataBoardDeleteChartById,
  merchantInsQueryTree,
  dataBoardReserveChart,
  dataBoardReportMerReMenuInsById,
  merchantReportmenuRemoveSubMerMenu,
  merchantReportProvideSel,
  merchantReportProvideSelSingle,
  merchantReportProvideUpda,
  merchantReportQueryData,
  merchantReportProvideUpdateSingle
} from '@/api/dataCenter/dataBoard.js';
// vuex
import store from "@/store";
// xlsx
import FileSaver from 'file-saver';
import * as XLSX from "xlsx";
// API
import { dataBoardByChartId, dataBoardMerchantGetChatData } from '@/api/dataCenter/dataBoard.js';
import { dateStrChangeTimeTamp } from './component/utils.js';
// img
import indexEmpty from '@/assets/dataCenter/dataB_indexEmpty.png';

export default {
  name: "dataCenter-board-template",
  components: {
    draggable,
    AppendChatDialog,
    Indicator,
    LineChart,
    LineTrendChart,
    BarChart,
    PieChart,
    Ranking,
    CommonTable,
    FunnelChart,
    BoardDialog,
    GroupDialog,
    MobileBoardDialog,
  },
  props: {
    service: {
      type: String,
      default: () => {
        return '';
      }
    },
    tooltipContent: {
      type: String,
      default: () => {
        return '';
      }
    },
    actId: {
      type: String,
      default: undefined
    }
  },
  provide: function () {
    return {
      actId: this.actId
    }
  },
  data() {
    return {
      indexEmpty,
      beanName: '',
      boardVisible: false,
      boardId: null,
      groupVisible: false,
      groupId: null,
      mobileBoardVisible: false,
      currentMenuName: null,
      chartId: null,
      form: {
        menu: '',
        organizationId: '',
        date: [],
        chartName: ''
      },
      filtrateDate: [],
      menuOptions: [],
      orgOptions: [],
      drag: false,
      appendChatVisible: false,
      handleMove,
      handleMore,
      tanhao,
      options: [
        {
          value: '1',
          label: '整体分析'
        },
        {
          value: '2',
          label: '概览分析'
        },
      ],
      props: {
        value: 'id',
        label: 'name',
        children: 'children',
        expandTrigger: 'hover',
      },
      templateList: [
        // {
        //   id: 1,
        //   name: '指标',
        //   size: 'mini',
        //   type: 'indicator',
        //   largeHeight: false,
        //   data: {
        //     // 对应指标查询的具体数据
        //     // 例如 title time 
        //   }
        // },
        // {
        //   id: 1,
        //   name: '指标',
        //   size: 'small',
        //   type: 'line',
        //   largeHeight: false,
        //   data: {
        //     // 对应指标查询的具体数据
        //     // 例如 title time 
        //   }
        // },
        // {
        //   id: 1,
        //   name: '指标',
        //   size: 'small',
        //   type: 'bar',
        //   largeHeight: false,
        //   data: {
        //     // 对应指标查询的具体数据
        //     // 例如 title time 
        //   }
        // },
      ],
      size: '' | 'large' | 'small',
      shortcuts: [
        {
          text: '昨天',
          value: () => {
            const start = new Date()
            start.setHours(0)
            start.setMinutes(0)
            start.setSeconds(0)
            start.setMilliseconds(0)
            start.setTime(start.getTime() - 3600 * 1000 * 24)
            const end = new Date(start.getTime() + 60 * 60 * 24 * 1000 - 1000)
            return [start, end]
          },
        },
        {
          text: '过去7天',
          value: () => {
            // const end = new Date()
            const start = new Date()
            start.setHours(0)
            start.setMinutes(0)
            start.setSeconds(0)
            start.setMilliseconds(0)
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            const end = new Date(start.getTime() + 60 * 60 * 24 * 7 * 1000 - 1000)
            return [start, end]
          },
        },
        {
          text: '过去14天',
          value: () => {
            // const end = new Date()
            const start = new Date()
            start.setHours(0)
            start.setMinutes(0)
            start.setSeconds(0)
            start.setMilliseconds(0)
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 14)
            const end = new Date(start.getTime() + 60 * 60 * 24 * 14 * 1000 - 1000)
            return [start, end]
          },
        },
        {
          text: '过去30天',
          value: () => {
            const start = new Date()
            start.setHours(0)
            start.setMinutes(0)
            start.setSeconds(0)
            start.setMilliseconds(0)
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            const end = new Date(start.getTime() + 60 * 60 * 24 * 30 * 1000 - 1000)
            return [start, end]
          },
        },
        {
          text: '过去2个月',
          value: () => {
            // const end = new Date()
            const start = new Date()
            start.setHours(0)
            start.setMinutes(0)
            start.setSeconds(0)
            start.setMilliseconds(0)
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 60)
            const end = new Date(start.getTime() + 60 * 60 * 24 * 60 * 1000 - 1000)
            return [start, end]
          },
        },
        {
          text: '过去3个月',
          value: () => {
            // const end = new Date()
            const start = new Date()
            start.setHours(0)
            start.setMinutes(0)
            start.setSeconds(0)
            start.setMilliseconds(0)
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            const end = new Date(start.getTime() + 60 * 60 * 24 * 90 * 1000 - 1000)
            return [start, end]
          },
        },
        {
          text: '过去6个月',
          value: () => {
            // const end = new Date()
            const start = new Date()
            start.setHours(0)
            start.setMinutes(0)
            start.setSeconds(0)
            start.setMilliseconds(0)
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 180)
            const end = new Date(start.getTime() + 60 * 60 * 24 * 180 * 1000 - 1000)
            return [start, end]
          },
        },
        {
          text: '过去12个月',
          value: () => {
            // const end = new Date()
            const start = new Date()
            start.setHours(0)
            start.setMinutes(0)
            start.setSeconds(0)
            start.setMilliseconds(0)
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 365)
            const end = new Date(start.getTime() + 60 * 60 * 24 * 365 * 1000 - 1000)
            return [start, end]
          },
        },
      ],
      reportData: [],
      payloadData: null,
      tableData: [],
      column: [],
      reportLinkChart: [],
      payloadData: {}
    };
  },
  watch: {

  },
  async mounted() {
    // 默认写死时间
    let start = new Date(new Date().getTime() - 24 * 60 * 60 * 1000 * 8);
    let end = new Date(new Date().getTime() - 24 * 60 * 60 * 1000 - 1000)
    this.form.date = [`${this.timestampToTime(start)} 00:00:00`, `${this.timestampToTime(end)} 23:59:59`]
    store.commit('SETSCREENTIME', this.form.date);
    // 优先获取机构数据
    // await this.merchantInsQueryTreeApi();
    // store.commit('GLOBALSERVERTYPE', 'activity')
    this.merchantReportProvideSelApi();
  },
  methods: {
    timestampToTime(timestamp) {
      var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var Y = date.getFullYear() + '-';
      var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
      var D = (date.getDate() < 10 ? `0${date.getDate()}` : date.getDate());
      return Y + M + D;
    },
    // 获取面板信息
    async merchantReportProvideSelApi() {
      let api = this.actId ? merchantReportProvideSelSingle : merchantReportProvideSel
      let res = await api({
        merchantId: store.state.user.merchantId,
        insId: store.state.insId.insId,
        service: this.service,
        actId: this.actId ?? undefined
      })
      if (res.code === 200) {
        this.payloadData = res.payload;
        this.templateList = JSON.parse(res.payload.datas);
        this.templateList.forEach(item => {
          if (item.type === 'lineTrend') {
            item.largeHeight = true;
          }

          //添加超过1个以上筛选条件标志
          if (item.fieldMapping) {
            item.showFilterData = Object.keys(item.fieldMapping).length > 1
          }
        })
        console.log(this.templateList, 'templateList')
      } else {
        this.templateList = [];
      }
    },
    // 保存面板数据
    async merchantReportProvideUpdaApi() {
      this.payloadData.datas = JSON.stringify(this.templateList)
      this.payloadData.actId=this.actId??undefined
      const api=this.actId?merchantReportProvideUpdateSingle:merchantReportProvideUpda
      let res = await api(this.payloadData);
      if (res.code === 200) {
        this.$message.success('更新保存成功！');
      }
    },
    // 新建菜单分组
    handleClickCreateMenu(val) {
      // 1 新建看板
      if (val === 1) {
        this.boardVisible = true;
        this.boardId = null;
      }
      // 2 新建分组
      if (val === 2) {
        this.groupVisible = true;
        this.groupId = null
      }
    },
    // 编辑菜单分组
    handleClickEditMenu(val) {
      // 1 编辑看板
      if (val === 1) {
        this.boardVisible = true;
        this.boardId = this.form.menu[1];
      }
      // 2 移动看板
      if (val === 2) {
        this.mobileBoardVisible = true;
      }
      // 3 删除看板
      if (val === 3) {
        ElMessageBox.confirm(`确认删除该看板吗？看板删除后,不可恢复！`, "删除提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          this.merchantReportmenuRemoveSubMerMenuApi();
        });
      }
      // 4 保存为PDF
      if (val === 4) {
        window.print();
      }
    },
    // 更新菜单
    async handleUpdateMenu(val) {
      let res = await dataBoardReportMerReMenuInsById({
        insId: this.form.organizationId,
        merchantId: store.state.user.merchantId,
        id: '1'
      });
      if (res.code === 200) {
        this.menuOptions = res.payload;
        // 遍历获取菜单name
        this.menuOptions.forEach(item => {
          if (item.children && item.children.length != 0) {
            item.children.forEach(value => {
              if (value.id === store.state.user.currentMenuId) {
                this.form.menu = [item.id, value.id];
                this.currentMenuName = value.name;
              }
            })
          }
        })
        // 置空操作ID
        this.boardId = null;
        this.groupId = null;
      }
    },
    // 删除看板Api
    async merchantReportmenuRemoveSubMerMenuApi() {
      let res = await merchantReportmenuRemoveSubMerMenu({
        id: this.form.menu[1]
      })
      if (res.code === 200) {
        ElMessage({
          type: "success",
          message: "删除看板成功",
        });
        // 默认菜单id 赋值vuex
        store.commit('SETCURRENTMENUID', null);
        // 获取菜单
        this.dataBoardReportMerReMenuInsByIdApi(this.form.organizationId, store.state.user.merchantId);
      }
    },
    // 选择时间段
    handleChangeDate(val) {
      console.log('enter here')
      store.commit('SETSCREENTIME', []);
      store.commit('SETSCREENTIME', val);
    },
    // 选择机构节点
    handleChangeOrganization(val) {
      console.log(val);
      store.commit('SETORGANIZATIONID', val[0]);
    },
    // 获取机构树Api
    async merchantInsQueryTreeApi() {
      let res = await merchantInsQueryTree()
      if (res.code === 200) {
        this.orgOptions = res.payload
        // 判断是否已选机构节点
        if (store.state.insId.insId) {
          // 取值vuex
          this.form.organizationId = store.state.insId.insId;
        } else {
          // 默认机构值val
          this.form.organizationId = this.orgOptions[0].id;
          // 更新vuex
          store.commit('SETORGANIZATIONID', this.form.organizationId);
        }
        // 获取菜单
        // this.dataBoardReportMerReMenuInsByIdApi(this.form.organizationId, store.state.user.merchantId);
        // this.dataBoardReportMenuListApi(store.state.user.merchantId);
        // 默认筛选时间
        if (store.state.user.screenTime && store.state.user.screenTime.length != 0) {
          this.form.date = store.state.user.screenTime;
        }
      }
    },
    // 获取菜单下所有图表数据Api
    async dataBoardByReportMenuIdApi(id) {
      let res = await dataBoardByReportMenuId({
        id,
        insId: this.form.organizationId
      });
      if (res.code === 200) {
        this.templateList = res.payload;
        this.templateList.forEach(item => {
          if (item.type === 'lineTrend') {
            item.largeHeight = true;
          }
        })
      } else {
        this.templateList = [];
      }
    },
    // 新增图表
    handleClickAppendChat() {
      this.chartId = null;
      this.appendChatVisible = true;
      console.log(this.templateList);
    },
    // item操作
    handleCommand(command, item) {
      console.log(item, 'handleCommand');
      if (command === 'edit') {
        this.appendChatVisible = true;
        this.reportLinkChart = item.support;
        this.beanName = item.beanName;
      } else if (command === 'del') {
        // ElMessageBox.confirm(`确认删除该报表吗？`, "删除提示", {
        //   confirmButtonText: "确认",
        //   cancelButtonText: "取消",
        //   type: "warning",
        // }).then(() => {
        //   this.dataBoardDeleteChartByIdApi(item.id);
        // });
      } else if (command === 'export') {
        // 下载
        this.dataBoardChartExportApi(item.beanName, item.chartName);
      } else {
        // 先置空
        store.commit('OPENDATASCREEN', null);
        // 数据展示筛选
        store.commit('OPENDATASCREEN', item.beanName);
      }
    },
    // 级联选择菜单
    handleChangeCascader(val) {
      if (val.length != 2) {
        ElMessage({
          type: "warning",
          message: "该分组下没有看板,请新增看板",
        });
        return false;
      }
      // 切换菜单更新vuex
      store.commit('SETCURRENTMENUID', val[1]);
      this.dataBoardByReportMenuIdApi(val[1]);
      // 遍历获取菜单name
      this.menuOptions.forEach(item => {
        if (item.children && item.children.length != 0) {
          item.children.forEach(value => {
            if (value.id === val[1]) {
              this.currentMenuName = value.name;
            }
          })
        }
      })
    },
    // 根据商户ID获取菜单列表Api(弃用)
    // async dataBoardReportMenuListApi(id) {
    //   let res = await dataBoardReportMenuList({
    //     id
    //   });
    //   if(res.code === 200) {
    //     this.menuOptions = res.payload;
    //     this.dataBoardByReportMenuIdApi(this.menuOptions[0].children[0].id);
    //     // 默认菜单id 赋值vuex
    //     store.commit('SETCURRENTMENUID', this.menuOptions[0].children[0].id);
    //     // 默认菜单val
    //     this.form.menu = [this.menuOptions[0].id, this.menuOptions[0].children[0].id];
    //     this.currentMenuName = this.menuOptions[0].children[0].name;
    //   }
    // },
    // 根据机构id获取菜单列表Api
    async dataBoardReportMerReMenuInsByIdApi(insId, merchantId) {
      let res = await dataBoardReportMerReMenuInsById({
        insId,
        merchantId,
        id: '1'
      });
      if (res.code === 200) {
        this.menuOptions = res.payload;
        if (store.state.user.currentMenuId) {
          console.log('enter you', this.menuOptions, store.state.user.currentMenuId)
          let currentMenuId = store.state.user.currentMenuId;
          this.dataBoardByReportMenuIdApi(currentMenuId);
          // 默认菜单val
          this.menuOptions.forEach(item => {
            if (item.children && item.children.length != 0) {
              item.children.forEach(value => {
                if (currentMenuId === value.id) {
                  this.form.menu = [item.id, value.id];
                  this.currentMenuName = value.name;
                }
              })
            }
          })
          console.log('this.form.menu', this.form.menu)
        } else {
          console.log('enter wu', this.menuOptions)
          let currentMenuId = null;
          let isStop = false;
          this.menuOptions.forEach(item => {
            if (item.children && item.children.length != 0 && !isStop) {
              currentMenuId = item.children[0].id
              this.dataBoardByReportMenuIdApi(currentMenuId);
              // 默认菜单id 赋值vuex
              store.commit('SETCURRENTMENUID', currentMenuId);
              // 默认菜单val
              this.form.menu = [item.id, currentMenuId];
              this.currentMenuName = item.children[0].name;
              isStop = true;
            }
          })
        }
      }
    },
    // 编辑图表
    handleClickConfirm(beanName, val) {
      console.log('beanName', beanName, val)
      this.templateList.forEach((item, index) => {
        console.log('item', item)
        if (item.beanName === beanName) {
          item.type = val.type;
          item.layoutType = val.layout;
          // 先设置假的 100毫秒后换回真的
          this.templateList[index].type = null;
          setTimeout(() => {
            this.templateList[index].type = val.type;
          }, 100)
        }
      })

    },
    // 删除图表Api
    async dataBoardDeleteChartByIdApi(id) {
      let res = await dataBoardDeleteChartById({
        id
      });
      if (res.code === 200) {
        this.templateList.forEach((item, index) => {
          if (item.id === id) {
            this.templateList.splice(index, 1);
          }
        });
        ElMessage({
          type: "success",
          message: "删除成功",
        });
      }
    },
    handleClickSave() {
      this.dataBoardReserveChartApi();
    },
    // 保存更新图标位置
    async dataBoardReserveChartApi() {
      this.templateList.forEach((item, index) => {
        item.sort = index + 1;
      })
      let res = await dataBoardReserveChart(this.templateList);
      if (res.code === 200) {
        ElMessage({
          type: "success",
          message: "更新排版成功",
        });
      }
    },
    // 下载导出
    dataBoardChartExportApi(id, chartName) {
      this.merchantReportQueryDataApi(id, chartName);
    },
    // 获取报表数据
    async merchantReportQueryDataApi(id, chartName) {
      // screenTime为菜单筛选时间
      let screenTime = store.state.user.screenTime;
      let startTime = '';
      let endTime = '';
      if (screenTime && screenTime.length != 0) {
        startTime = dateStrChangeTimeTamp(screenTime[0]);
        endTime = dateStrChangeTimeTamp(screenTime[1]);
      }
      let paramStr = {
        startTime,
        endTime,
        chartType: 2,
        toIndex: null,
        insId: store.state.insId.insId,
        mallId: store.state.user.mallId || '',
        actId:this.actId??undefined,
        field:store.state.user.queryConditionObj[id+'Key']
      }
      console.log(store.state.user.queryConditionObj[id+'Key'],"099988");
      paramStr[store.state.user.queryConditionObj.queryConditionKey] = store.state.user.queryConditionObj.queryConditionVal;
      paramStr = JSON.stringify(paramStr);
      let res = await merchantReportQueryData({
        beanName: id,
        param: paramStr
      })
      if (res.code === 200) {
        this.payloadData = res.payload;
        this.capsulationDealData(chartName)
      }
    },
    // 处理数据
    capsulationDealData(chartName) {
      if (Object.keys(this.payloadData).length === 0) return false;
      let dataValue = this.payloadData.data;
      let column = [];
      dataValue.x.forEach((item, index) => {
        let obj = {
          prop: "",
          align: "",
          label: "",
          scopeStatus: true,
          width: "",
          minWidth: ""
        }
        obj.prop = item + index;
        obj.label = item;
        column.push(obj);
      })

      let tableData = [];

      dataValue.y.forEach((val1, key1) => {
        let obj = {};
        for (let key2 = 0; key2 < val1.length; key2++) {
          for (let index = 0; index < dataValue.x.length; index++) {
            if (index == key2) {
              obj[dataValue.x[index] + index] = val1[key2].val;
            }
          }
        }
        tableData.push(obj);
      })
      console.log('column', column)
      console.log('tableData', tableData)
      this.column = column;
      this.tableData = tableData;
      let excelName = '';
      excelName = chartName + '(' + store.state.user.screenTime[0] + '至' + store.state.user.screenTime[1] + ')';
      this.$nextTick(() => {
        this.exportExcel(excelName);
      })
    },
    // 导出excel
    exportExcel(excelName) {
      try {
        const $e = this.$refs['report-table'].$el
        let $table = $e.querySelector('.el-table__fixed')
        if (!$table) {
          $table = $e
        }
        const wb = XLSX.utils.table_to_book($table, { raw: true })
        const wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
        FileSaver.saveAs(
          new Blob([wbout], { type: 'application/octet-stream' }),
          `${excelName}.xlsx`,
        )
      } catch (e) {
        if (typeof console !== 'undefined') console.error(e)
      }
    }
  },
  computed: {
    dragOptions() {
      return {
        animation: 200,
        group: "",
        disabled: false,
        ghostClass: "ghost",
        handle: '.handle'
      };
    }
  }
};
</script>

<style lang="scss" scoped>
.dataCenter-board-template {
  width: 100%;
  height: 100%;
  position: relative;
  background: #f7f8fa;

  :deep(.icon-arrow-down:before) {
    display: none;
  }

  .templateHeader {
    z-index: 9999;
    width: 100%;
    // height: 56px;
    padding: 14px 4px;
    background: #fff;
    box-sizing: border-box;
    margin: 0 0 0.5% 0;
    display: flex;
    justify-content: space-between;
    align-items: center;

    &-left {
      font-size: 18px;
      color: #252934;
      font-weight: 600;
      min-width: 200px;
      display: flex;
      align-items: center;
      justify-content: flex-start;

      .handle-tanhao {
        width: 16px;
        height: 16px;
        cursor: pointer;
      }
    }

    &-right {
      min-width: 460px;
      height: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    :deep(.el-form-item) {
      margin-bottom: 0;
      margin-right: 4px;
    }

    :deep(.el-form-item__label) {
      font-weight: 600;
    }
  }

  .templateComponents {
    width: 100%;
    height: 100%;

    // background: pink;
    #draggable {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: flex-start;
      justify-content: flex-start;
      flex-wrap: wrap;

      .list-group-item {
        height: 380px;
        padding: 20px;
        background: #fff;
        box-sizing: border-box;
        position: relative;

        &:hover {
          box-shadow: 0 0 16px 2px rgb(0 31 86 / 10%);
        }

        .dragIcon {
          position: absolute;
          left: 0;
          top: 0;
          width: 100%;
          height: 20px;
          display: flex;
          justify-content: center;
          align-items: center;

          .handle {
            display: none;
          }
        }

        &:hover .dragIcon .handle {
          display: block;
          cursor: pointer;
        }

        .operaIcon {
          position: absolute;
          top: 20px;
          right: 20px;
          display: none;
          z-index: 990;
        }

        &:hover .operaIcon {
          display: block;
        }
      }

      .medium {
        width: 99%;
        margin: 0.5%;
      }

      .small {
        width: 49%;
        margin: 0.5%;
      }

      .mini {
        width: 24%;
        margin: 0.5%;
        height: 182px;
      }

      .largeHeight {
        height: 538px;
      }
    }
  }

  .templateComponents-else {
    width: 100%;
    height: 700px;
    background: #fff;
    display: flex;
    align-items: center;
    justify-content: center;

    .empty {
      width: 240px;
      height: 254px;

      &-img {
        width: 100%;
        height: 160px;
        text-align: center;

        .img {
          width: 160px;
          height: 100%;
        }
      }

      &-text {
        width: 100%;
        height: 20px;
        font-size: 14px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #909399;
        text-align: center;
        line-height: 20px;
        margin: 20px 0;
      }

      &-btn {
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }

  .templateComponents-table {
    width: 0;
    height: 0;
  }
}
</style>